package v1

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"mindonmap/models"
	"mindonmap/pkgs/setting"
	"net/http"
	"strings"
	"time"

	"github.com/gin-contrib/sessions"

	jwt "github.com/appleboy/gin-jwt/v2"
	"github.com/gin-gonic/gin"

	"mindonmap/pkgs/e"
)

type LoginsFormInfo struct {
	Email    string `json:"email"`
	Password string `json:"password"`
	EId      string `json:"e_id"`
}

func GetUserInfo(c *gin.Context) {
	claims := jwt.ExtractClaims(c)
	userName := claims["username"].(string)
	params := claims["token"].(string)
	code := e.SUCCESS
	//userRoles := models.GetRoles(userName)

	// curl
	v := fmt.Sprintf("%s", params)
	// fmt.Println("yonghu:")
	// fmt.Println(v)
	baseurl := setting.GetLoginurl() + "/account/profile"
	client := &http.Client{Timeout: 60 * time.Second}
	responseToken, err := client.Post(baseurl, "application/x-www-form-urlencoded", strings.NewReader(v))
	if err != nil {
		fmt.Println(err)
	}
	defer responseToken.Body.Close()
	body, err := ioutil.ReadAll(responseToken.Body)
	if err != nil {
		fmt.Println(err)
	}
	var datas models.Webinfo
	err = json.Unmarshal(body, &datas)
	var data models.User
	if err != nil {
		data = models.User{UserName: userName, Avatar: ""}
	} else {
		data = models.User{UserName: userName, Avatar: datas.Picture}
	}

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMsg(code),
		"data": data,
	})
}

func Logincheck(c *gin.Context) {

	var jsons LoginsFormInfo
	if err := c.BindJSON(&jsons); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": e.INVALID_PARAMS,
			"msg":  e.GetMsg(e.INVALID_PARAMS),
			"data": make(map[string]interface{}),
		})
		return
	}
	v := "email=" + jsons.Email + "&password=" + jsons.Password + "&e_id=" + jsons.EId
	baseurl := setting.GetLoginurl() + "/account/email/login"
	responseToken, _ := http.Post(baseurl, "application/x-www-form-urlencoded", strings.NewReader(v))
	defer responseToken.Body.Close()
	body, err := ioutil.ReadAll(responseToken.Body)

	if err != nil {
		fmt.Println(err)
	}
	code := e.SUCCESS
	var data map[string]interface{}
	err = json.Unmarshal(body, &data)
	if err != nil {
		fmt.Println(err)
	}
	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  "",
		"data": data,
	})
}

func Logout(c *gin.Context) {
	session := sessions.Default(c)
	session.Delete("user_id")
	session.Save() // 保存修改
	code := e.SUCCESS
	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMsg(code),
		"data": "success",
	})
}
